package com.basic.business.smb.service.impl;

import com.basic.common.constant.CacheConstants;
import com.basic.common.core.redis.RedisCacheUtils;
import com.basic.common.utils.smbUtils.CIFSContextWrapper;
import com.basic.common.utils.smbUtils.CifsContextPoolUtils;
import jcifs.CIFSContext;

import jcifs.smb.SmbFile;
import org.springframework.stereotype.Service;
import com.basic.common.core.service.impl.BaseServiceImpl;
import com.basic.business.smb.domain.TSmbMgmt;
import com.basic.business.smb.service.ITSmbMgmtService;
import com.basic.business.smb.mapper.TSmbMgmtMapper;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * 业务-SMB管理Service业务层处理
 *
 * @author zhaoxy_jn@163.com
 */
@Service
public class TSmbMgmtServiceImpl extends BaseServiceImpl<TSmbMgmtMapper,TSmbMgmt> implements ITSmbMgmtService {

    @Resource
    private TSmbMgmtMapper tSmbMgmtMapper;

    /**
     * 项目启动时，初始化SMB信息缓存
     */
    @PostConstruct
    public void init(){
        resetSmbCache();
    }



    @Override
    public boolean testConnection(TSmbMgmt tSmbMgmt) {
        // 初始化连接池
        CifsContextPoolUtils.initPool(tSmbMgmt.getUserName(), tSmbMgmt.getPassword());

        try (CIFSContextWrapper wrapper = new CIFSContextWrapper(CifsContextPoolUtils.borrowContext())) {
            CIFSContext context = wrapper.getContext();
            try (SmbFile smbFile = new SmbFile(tSmbMgmt.getSmbPath(), context)) {
                smbFile.connect(); // 尝试连接
                return true;
            }
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public int updateStatusByIds(String[] ids, String status) {
        return tSmbMgmtMapper.updateStatusByIds(ids, status);
    }

    @Override
    public int updateMountStatusByIds(String[] ids, String status) {
        return tSmbMgmtMapper.updateMountStatusByIds(ids, status);
    }

    @Override
    public boolean isExistMountSMB() {
        return tSmbMgmtMapper.getMountCount() > 0;
    }

    @Override
    public void resetSmbCache() {
        // 清空缓存
        RedisCacheUtils.clearCache(CacheConstants.SMB_REDIS_KEY + "*");
        // 加载缓存
        loadingSmbCache();
    }

    /**
     * 加载SMB信息缓存
     */
    private void loadingSmbCache() {
        RedisCacheUtils.setCacheObject(CacheConstants.SMB_REDIS_KEY, tSmbMgmtMapper.getNormalMountSmbInfo());
    }
}
